<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2006/12/22 10:13:57 $)
// $RCSfile: functions_views.php,v $ : $Revision: 1.3 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Renders the Ticket View Insert/Edit Form
*/
function renderViewForm($type)
{
	global $_SWIFT, $dbCore, $_fieldpointer;

	printFormStart("viewform", "index.php", "POST", false, "", "javascript:return processViewForm();");
	printMainTableHeader(iif($type==INSERT,$_SWIFT["language"]["insertticketview"], $_SWIFT["language"]["editticketview"]));

	printTextRow("title", $_SWIFT["language"]["viewtitle"], $_SWIFT["language"]["desc_viewtitle"], "text", $_POST["title"]);

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["viewunassigned"];
	$options[0]["value"] = VIEW_UNASSIGNED;

	if ($type == INSERT)
	{
		$options[0]["checked"] = true;
	} else if ($type == EDIT && $_POST["viewunassigned"] == 1) {
		$options[0]["checked"] = true;
	}

	$options[1]["title"] = $_SWIFT["language"]["viewassignedme"];
	$options[1]["value"] = VIEW_ASSIGNED;

	if ($type == INSERT)
	{
		$options[1]["checked"] = true;
	} else if ($type == EDIT && $_POST["viewassigned"] == 1) {
		$options[1]["checked"] = true;
	}

	$options[2]["title"] = $_SWIFT["language"]["viewalltickets"];
	$options[2]["value"] = VIEW_ALLTICKETS;

	if ($type == INSERT)
	{
		$options[2]["checked"] = false;
	} else if ($type == EDIT && $_POST["viewalltickets"] == 1) {
		$options[2]["checked"] = true;
	}

	printCheckboxListRow("viewtickettypes", $_SWIFT["language"]["vassignedto"], $_SWIFT["language"]["desc_vassignedto"], $options);

	printPublicPrivateRow("viewtype", $_SWIFT["language"]["viewtype"], $_SWIFT["language"]["desc_viewtype"], iif($type==EDIT, iif($_POST["viewtype"] == VIEW_PUBLIC, true, false), true));

	$fieldoptions = array();
	$index = 0;
	foreach ($_fieldpointer as $key=>$val)
	{
		if ($val["type"] != "custom")
		{
			$fieldoptions[$index]["title"] = $val["title"];
			$fieldoptions[$index]["value"] = $key;
			$index++;
		}
	}
	$fieldoptions[0]["selected"] = true;
	printSelectRow("sortby", $_SWIFT["language"]["sortby"], $_SWIFT["language"]["desc_sortby"], $fieldoptions);

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["viewasc"];
	$options[0]["value"] = VIEW_ASC;
	$options[1]["title"] = $_SWIFT["language"]["viewdesc"];
	$options[1]["value"] = VIEW_DESC;
	$options[1]["selected"] = true;

	printSelectRow("sortorder", $_SWIFT["language"]["sortorder"], $_SWIFT["language"]["desc_sortorder"], $options);

	printNumberRow("ticketsperpage", $_SWIFT["language"]["ticketsperpage"], $_SWIFT["language"]["desc_ticketsperpage"], iif(empty($_POST["ticketsperpage"]), 20, intval($_POST["ticketsperpage"])));

	// Now we process the custom fields
	$_cfgroups = $customfieldgroupidlist = $_customfields = array();
	//Mahesh Slaria: Staff & user ticket creation
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldgroups` WHERE `grouptype` IN ('". CUSTOMFIELD_STAFFTICKET ."', '". CUSTOMFIELD_USERTICKET ."', '". CUSTOMFIELD_STAFFUSERTICKET ."') ORDER BY `displayorder` ASC;");
	while ($dbCore->nextRecord())
	{
		$_cfgroups[$dbCore->Record["customfieldgroupid"]] = $dbCore->Record;
		$customfieldgroupidlist[] = $dbCore->Record["customfieldgroupid"];
	}

	if (count($customfieldgroupidlist))
	{
		// Now fetch all the subsequent fields
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfields` WHERE `customfieldgroupid` IN (". buildIN($customfieldgroupidlist) .");");
		while ($dbCore->nextRecord())
		{
			$_customfields[$dbCore->Record["customfieldid"]] = $dbCore->Record;
			$_cfgroups[$dbCore->Record["customfieldgroupid"]]["fields"][$dbCore->Record["customfieldid"]] = &$_customfields[$dbCore->Record["customfieldid"]];
		}
	}

	// Now convert it all to options
	$fieldoptindex = count($fieldoptions);
	unset($opttext);
	if ($fieldoptindex)
	{
		foreach ($_cfgroups as $key=>$val)
		{
			$opttext .= '<optgroup label="'. $val["title"] .'">'.SWIFT_CRLF;
			if (_is_array($val["fields"]))
			{
				foreach ($val["fields"] as $fieldkey=>$fieldval)
				{
					$opttext .= '<option value="c'. intval($fieldval["customfieldid"]) .'">'. htmlspecialchars($fieldval["title"]) .'</option>'.SWIFT_CRLF;
				}
			}
			$opttext .= '</optgroup>';
		}
	}

	$fieldoptions2 = array();
	if ($type == INSERT)
	{
		$fieldoptions2 = array();
	} else if ($type == EDIT && !empty($_POST["ticketviewid"])) {
		$fieldoptions2 = array();
		$optindex = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketviewfields` WHERE `ticketviewid` = '". intval($_POST["ticketviewid"]) ."' ORDER BY `ticketviewfieldid` ASC;");
		while ($dbCore->nextRecord())
		{
			if ($dbCore->Record["ticketviewfieldtype"] == VIEWFIELD_LINK)
			{
				$fieldoptions2[$optindex]["title"] = $_fieldpointer[$dbCore->Record["fieldlinkid"]]["title"];
				$fieldoptions2[$optindex]["value"] = $dbCore->Record["fieldlinkid"];
				$optindex++;
			} else if ($dbCore->Record["ticketviewfieldtype"] == VIEWFIELD_CUSTOM) {
				$fieldoptions2[$optindex]["title"] = $_customfields[$dbCore->Record["customfieldid"]]["title"];
				$fieldoptions2[$optindex]["value"] = "c".$dbCore->Record["customfieldid"];
				$optindex++;
			}
		}
	}

	printSelectChoiceRow("fields", $_SWIFT["language"]["fieldstodisplay"], $_SWIFT["language"]["desc_fieldstodisplay"], $fieldoptions, $fieldoptions2, $opttext);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insert"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", iif($type==INSERT,"newticketview", "editticketview"));
	addHiddenField("step", "1");
	addHiddenField("departmentid", intval($_REQUEST["departmentid"]));
	addHiddenField("ticketstatusid", intval($_REQUEST["ticketstatusid"]));
	addHiddenField("ticketsearchid", intval($_REQUEST["ticketsearchid"]));
	if ($type == EDIT)
	{
		addHiddenField("ticketviewid", $_POST["ticketviewid"]);
	}
	printFormEnd();
}

/**
* Process post data for fields
*/
function processFieldsFromPost($fields)
{
	global $_SWIFT;

	if (!_is_array($fields))
	{
		return false;
	}

	$_fields = array();
	$index = 0;
	foreach ($fields as $key=>$val)
	{
		if (substr($val,0,1) == "c")
		{
			$_fields[$index]["type"] = VIEWFIELD_CUSTOM;
			$_fields[$index]["customfieldid"] = intval(substr($val, 1));
		} else {
			$_fields[$index]["type"] = VIEWFIELD_LINK;
			$_fields[$index]["fieldlinkid"] = intval($val);
		}
		$index++;
	}

	return $_fields;
}

/**
* Update existing ticket view
*/
function updateTicketView($ticketviewid, $title, $viewtype, $viewalltickets, $viewunassigned, $viewassigned, $sortby, $sortorder, $ticketsperpage, $fields, $ismaster = false)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($fields))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketviews` SET `title` = '". $dbCore->escape($title) ."', `viewtype` = '". intval($viewtype) ."', `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `viewalltickets` = '". iif($viewalltickets==true, "1", "0") ."', `viewunassigned` = '". iif($viewunassigned==true, "1", "0") ."', `viewassigned` = '". iif($viewassigned==true, "1", "0") ."', `sortby` = '". intval($sortby) ."', `sortorder` = '". intval($sortorder) ."', `dateline` = '". DATENOW ."', `ticketsperpage` = '". intval($ticketsperpage) ."' WHERE `ticketviewid` = '". intval($ticketviewid) ."';");

	$fieldsql = array();
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketviewfields` WHERE `ticketviewid` = '". intval($ticketviewid) ."';");
	foreach ($fields as $key=>$val)
	{
		// We insert a custom field into the grid
		if ($val["type"] == VIEWFIELD_CUSTOM && !empty($val["customfieldid"]))
		{
			$fieldsql[] = "('". intval($ticketviewid) ."', '". VIEWFIELD_CUSTOM ."', '". intval($val["customfieldid"]) ."', '0')";
		} else {
			// We insert a normal field
			$fieldsql[] = "('". intval($ticketviewid) ."', '". VIEWFIELD_LINK ."', '0', '". intval($val["fieldlinkid"]) ."')";
		}
	}

	if (count($fieldsql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketviewfields` (`ticketviewid`, `ticketviewfieldtype`, `customfieldid`, `fieldlinkid`) VALUES ". implode(",",$fieldsql).";");
	}

	rebuildTicketViewsCache();
}

/**
* Creates a new Ticket View
*/
function createTicketView($title, $viewtype, $viewalltickets, $viewunassigned, $viewassigned, $sortby, $sortorder, $ticketsperpage, $fields, $ismaster = false)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($fields))
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketviews` (`title`, `viewtype`, `staffid`, `viewalltickets`, `viewunassigned`, `viewassigned`, `sortby`, `sortorder`, `ismaster`, `dateline`, `ticketsperpage`) VALUES ('". $dbCore->escape($title) ."', '". intval($viewtype) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". iif($viewalltickets==true, "1", "0") ."', '". iif($viewunassigned==true, "1", "0") ."', '". iif($viewassigned==true, "1", "0") ."', '". intval($sortby) ."', '". intval($sortorder) ."', '". iif($ismaster==true, "1", "0") ."', '". DATENOW ."', '". intval($ticketsperpage) ."');");
	$ticketviewid = $dbCore->lastInsertId();
	if (!$ticketviewid)
	{
		return false;
	}

	$fieldsql = array();
	foreach ($fields as $key=>$val)
	{
		// We insert a custom field into the grid
		if ($val["type"] == VIEWFIELD_CUSTOM && !empty($val["customfieldid"]))
		{
			$fieldsql[] = "('". intval($ticketviewid) ."', '". VIEWFIELD_CUSTOM ."', '". intval($val["customfieldid"]) ."', '0')";
		} else {
			// We insert a normal field
			$fieldsql[] = "('". intval($ticketviewid) ."', '". VIEWFIELD_LINK ."', '0', '". intval($val["fieldlinkid"]) ."')";
		}
	}

	if (count($fieldsql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketviewfields` (`ticketviewid`, `ticketviewfieldtype`, `customfieldid`, `fieldlinkid`) VALUES ". implode(",",$fieldsql).";");
	}

	rebuildTicketViewsCache();
}

/**
* Delets the given ticket views
*/
function deleteTicketViews($ticketviewidlist)
{
	global $dbCore;

	if (!_is_array($ticketviewidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketviews` WHERE `ticketviewid` IN (". buildIN($ticketviewidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketviewfields` WHERE `ticketviewid` IN (". buildIN($ticketviewidlist) .");");
	$dbCore->query("UPDATE `". TABLE_PREFIX ."staff` SET `ticketviewid` = '1' WHERE `ticketviewid` IN (". buildIN($ticketviewidlist) .");");

	rebuildTicketViewsCache();

	require_once ("./includes/functions_staff.php");
	rebuildStaffCache();

	return false;
}

/**
* Rebuild the Ticket View Cache
*/
function rebuildTicketViewsCache()
{
	global $dbCore, $datastore;

	$_ticketviews = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketviews` ORDER BY `ticketviewid` ASC;");
	$index = 0;
	while ($dbCore->nextRecord())
	{
		$_ticketviews[$dbCore->Record["ticketviewid"]] = $dbCore->Record;
		$_ticketviews[$dbCore->Record["ticketviewid"]]["index"] = $index;
		$index++;
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketviewfields` ORDER BY `ticketviewfieldid` ASC;");
	while ($dbCore->nextRecord())
	{
		$ref = &$_ticketviews[$dbCore->Record["ticketviewid"]]["fields"];
		$ref[$dbCore->Record["ticketviewfieldid"]] = $dbCore->Record;
	}

	$datastore->update("ticketviewcache", $_ticketviews);
}
?>